package com.ruoyi.project.channel.salesmanScore.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.project.channel.payerBusinessInfo.domain.PayerBusinessInfo;
import com.ruoyi.project.channel.payerBusinessInfo.service.IPayerBusinessInfoService;
import com.ruoyi.project.channel.payerInfo.domain.PayerInfo;
import com.ruoyi.project.channel.payerInfo.service.IPayerInfoService;
import com.ruoyi.project.pay.PayConfig;
import com.ruoyi.project.pay.ThirdPayerServiceImpl;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.ISysUserService;
import com.ruoyi.project.system.user.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import com.ruoyi.project.channel.salesmanScore.mapper.SalesmanScoreMapper;
import com.ruoyi.project.channel.salesmanScore.domain.SalesmanScore;
import com.ruoyi.project.channel.salesmanScore.service.ISalesmanScoreService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.web.client.RestTemplate;

/**
 * 业务员加减分 服务层实现
 * 
 * @author CAIN
 * @date 2025-01-01
 */
@Service
public class SalesmanScoreServiceImpl implements ISalesmanScoreService 
{
	@Autowired
	private SalesmanScoreMapper salesmanScoreMapper;
	@Autowired
	private IPayerBusinessInfoService payerBusinessInfoService;
	@Autowired
	private IPayerInfoService payerInfoService;
	@Autowired
	private IUserService sysUserService;
	@Autowired
	private PayConfig payConfig;

	private static final Logger log = LoggerFactory.getLogger(SalesmanScoreServiceImpl.class);
	/**
     * 查询业务员加减分信息
     * 
     * @param userId 业务员加减分ID
     * @return 业务员加减分信息
     */
    @Override
	public SalesmanScore selectSalesmanScoreById(Long userId)
	{
	    return salesmanScoreMapper.selectSalesmanScoreById(userId);
	}
	
	/**
     * 查询业务员加减分列表
     * 
     * @param salesmanScore 业务员加减分信息
     * @return 业务员加减分集合
     */
	@Override
	public List<SalesmanScore> selectSalesmanScoreList(SalesmanScore salesmanScore)
	{
	    return salesmanScoreMapper.selectSalesmanScoreList(salesmanScore);
	}
	
    /**
     * 新增业务员加减分
     * 
     * @param salesmanScore 业务员加减分信息
     * @return 结果
     */
	@Override
	public int insertSalesmanScore(SalesmanScore salesmanScore)
	{

		salesmanScore.setCreateDate(new Date());
		if (salesmanScore.getInScore() == null || salesmanScore.getInScore().compareTo(BigDecimal.ZERO) != 0) {
			// 需要总后台上分
			PayerBusinessInfo search = new PayerBusinessInfo();
			search.setBusinessName("代理中心商户");
			List<PayerBusinessInfo> payerBusinessInfos = payerBusinessInfoService.selectPayerBusinessInfoList(search);
			PayerBusinessInfo payerBusinessInfo = payerBusinessInfos.get(0);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append("businessId=").append(payerBusinessInfo.getBusinessNo());
			stringBuilder.append("&payType=").append("107");
			Long childOrderno = System.currentTimeMillis();
			stringBuilder.append("&childOrderno=").append(childOrderno);
			stringBuilder.append("&amount=").append(salesmanScore.getInScore());
			String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			stringBuilder.append("&time=").append(time);
			stringBuilder.append("&").append(payerBusinessInfos.get(0).getApiKey());
			String sign = "";
			try {
				log.info("setToNextOrderString:" + stringBuilder.toString());
				sign = Md5Utils.androidMD5(stringBuilder.toString());
				System.out.println("setToNextOrderStringSign:" + sign);
			} catch (Exception e) {
			}
			RestTemplate restTemplate = new RestTemplate();
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("businessId", payerBusinessInfo.getBusinessNo());
			jsonObject.put("payType", "107");
			jsonObject.put("childOrderno", childOrderno);
			jsonObject.put("amount", salesmanScore.getInScore());
			jsonObject.put("addSalesmanScore", "true");
			jsonObject.put("time", time);
			jsonObject.put("sign", sign);
			String callbackUrl = "";
			if (salesmanScore.getInScore().compareTo(BigDecimal.ZERO) < 0) {
				// 负数
				callbackUrl =payConfig.getPayCenterHost() + "/admin/pay/order/patch";
				salesmanScore.setInScore(BigDecimal.ZERO);
			}
			jsonObject.put("serverUrl", callbackUrl);
			jsonObject.put("returnUrl", callbackUrl);
			User user = sysUserService.selectUserById(salesmanScore.getUserId());
			jsonObject.put("payerUserName", user.getLoginName());
			jsonObject.put("fromAlipayAccount", salesmanScore.getUserId()); // usdt地址
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
			HttpEntity<String> entity = new HttpEntity<String>(jsonObject.toJSONString(), headers);

			PayerInfo payerInfo = payerInfoService.selectPayerInfoById(payerBusinessInfo.getPayerId());
			JSONObject body = restTemplate.exchange(payerInfo.getServiceUrl(), HttpMethod.POST, entity, JSONObject.class).getBody();
			log.info("setToNextOrder:" + body.toJSONString());
		}
		salesmanScoreMapper.insertSalesmanScore(salesmanScore);
	    return 1;
	}
	
	/**
     * 修改业务员加减分
     * 
     * @param salesmanScore 业务员加减分信息
     * @return 结果
     */
	@Override
	public int updateSalesmanScore(SalesmanScore salesmanScore)
	{
	    return salesmanScoreMapper.updateSalesmanScore(salesmanScore);
	}

	/**
     * 删除业务员加减分对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteSalesmanScoreByIds(String ids)
	{
		return salesmanScoreMapper.deleteSalesmanScoreByIds(Convert.toStrArray(ids));
	}
	
}
